package org.rocketmq.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.exception.MQClientException;
import org.rocketmq.template.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.Assert;

/**
 * @author zd
 * @date 2023/2/1 16:34
 * @description rocketmq配置
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(RocketMQProperties.class)
@ConditionalOnProperty(prefix = "rocketmq", value = "name-server", matchIfMissing = true)
public class RocketMQConfig {

    @Bean(name = "rocketMQProducer", initMethod = "initMQProducer", destroyMethod = "close")
    public RocketMQProducer defaultMQProducer(RocketMQProperties properties) throws MQClientException {
        RocketMQProperties.Producer producerProperties = properties.getProducer();
        String nameServer = properties.getNameServer();
        String group = producerProperties.getGroup();

        Assert.hasText(nameServer, "[rocketmq.name-server] 不允许为空");
        Assert.hasText(group, "[rocketmq.producer.group] 不允许为空");

        // 创建消息生产者
        RocketMQProducer producer = new RocketMQProducer();
        producer.setNamesrvAddr(nameServer);
        producer.setProduceGroup(group);
        log.info("nameserver {} producer初始化", nameServer);
        return producer;
    }

    @Bean
    public RocketMQTemplate rocketMQTemplate(@Qualifier("rocketMQProducer") RocketMQProducer producer) {
        RocketMQTemplate template = new RocketMQTemplate();
        template.setDefaultMQProducer(producer.getDefaultMQProducer());
        template.setTransactionMQProducer(producer.getTransactionMQProducer());
        return template;
    }

    @Bean
    public RocketMQConsumer rocketMQConsumer(RocketMQProperties properties) {
        String nameServer = properties.getNameServer();
        Assert.hasText(nameServer, "[rocketmq.name-server] 不允许为空");

        RocketMQConsumer consumer = new RocketMQConsumer();
        consumer.setNamesrvAddr(nameServer);
        return consumer;
    }
}
